import luchRequest from "luch-request";
import store from '@/store'
import businessError from '@/common/businessError.js'
import {baseUrl} from '@/common/const.js'

const service = new luchRequest();
//const token = uni.getStorageSync('ACCESS_TOKEN');
service.setConfig((config) => {
	/* 设置全局配置 */
	//config.baseURL = "http://pigx-gateway:9999" /* 根域名不同 */
	config.baseURL = baseUrl//"https://m.ylggz.com.cn" /* 根域名不同 */
	config.header = {
		...config.header,
		// 'Authorization': "Basic c29jaWFsOnNvY2lhbA==",
		// 'Tenant-ld': process.env.VUE_APP_TENANT_lD // 默认租户
	}
	return config;
})
/**
 * 请求拦截
 */
service.interceptors.request.use((config) => {
	// 租户
	config.header = {
		...config.header,
		'Tenant-ld': '1',
	}
	const isToken = (config.custom.isToken || {}).isToken === false
	const token = store.getters.accessToken
	
	if (token && !isToken) {
		config.header.Authorization = token
	}
	if (config.custom.loading) {
		uni.showLoading({
			mask: true
		});
	}
	return config;
})
/**
 * 响应拦截
 */
service.interceptors.response.use(async (response) => {
	uni.hideLoading();
	// 请求错误
	let msg = '';
	if (!response.data && !response.statusCode) {
		uni.showToast({
			icon: "none",
			title: '服务器无响应！'
		});
		return Promise.reject('服务器无响应')
	}
	const status = Number(response.statusCode) || 200
	// 后台定义 424 针对令牌过去的特殊响应码
	if (status === 424) {
		// 令牌过期
		businessError.tokenExpire()
		return Promise.reject()
	}
	
	if(status == 401){
		uni.showToast({
			icon: "none",
			title: response.data.msg
		});
		return Promise.reject()
	}
	if (status !== 200 || (response.data.code !== undefined && response.data.code !== 0 && response.data.code !== 200)) {
		switch(response.data.code){
			case 1:
				uni.showToast({
					icon: "none",
					title: response.data.msg
				});
				break;
			default:
				return Promise.reject(response.data)
		}
		return Promise.reject()
	}	
	return response.data;
}, response => {
	uni.hideLoading();
	const status = Number(response.statusCode)
	
	if(status == 401 || status == 428){
		uni.showToast({
			icon: "none",
			title: response.data.msg
		});
		return Promise.reject()
	}
	
	// token过期
	if(status == 424){
		businessError.tokenExpire()
		return Promise.reject()
	}
	
	// token过期
	if(status == 500){
		uni.showToast({
			icon: "none",
			title: '系统错误'
		});
		return Promise.reject()
	}
	
	if (!response.data && !response.statusCode) {
		uni.showToast({
			icon: "none",
			title: '服务器无响应！'
		});
		return Promise.reject('服务器无响应')
	}
})

export default service;